package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.example.entity.Person;
import com.example.service.ExternalDataImporterService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ExternalDataImporterServiceImpl implements ExternalDataImporterService {

    @Override
    public String easyExcelDemo(HttpServletResponse resp) {
        // 设置响应头
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Disposition", "attachment; filename=data.xlsx");
        try {
            EasyExcel.write(resp.getOutputStream(), Person.class).sheet("数据").doWrite(data());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return "ok";
    }

    private List<Person> data() {
        List<Person> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            Person data = new Person();
            data.setId((long) i);
            data.setName("字符串" + i);
            data.setAge(1);
            list.add(data);
        }
        return list;
    }
}
